import datetime
import tracemalloc
from contextlib import asynccontextmanager

from apscheduler.executors.asyncio import AsyncIOExecutor
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from fastapi import FastAPI
from modules.admin.services.order import OrderServices
from app.models.Orders import Orders

tracemalloc.start()
scheduler = AsyncIOScheduler()
scheduler.add_executor(AsyncIOExecutor())


def update_status(order_id):
    print(order_id)
    data = Orders.find(order_id)
    if data.status == "pending":
        data.update({"status": "cancelled"})
        print({"msg": f'订单已取消===>{order_id}'})
        return
    print({"msg": "订单状态不正确"})


# 添加任务
def add_task(task_id: str, run_date: datetime.datetime, args: list):
    try:
        scheduler.add_job(update_status, id=task_id, trigger='date', run_date=run_date, args=args)
    except Exception as e:
        print(e)
        print({"msg": "任务启动失败"})
    print({"msg": "任务启动成功"})


@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动调度器
    print('scheduler start')
    scheduler.start()
    # 更新所有订单状态为取消
    await OrderServices.all_status_update("pending", "cancelled")
    # all_status_update_task("all_status_update", datetime.datetime.now() + datetime.timedelta(seconds=10), [])
    # 应用关闭时的处理
    yield
    print('end')
    scheduler.remove_all_jobs()
    # 关闭调度器
    scheduler.shutdown()
